package com.itheima.controller;

import com.itheima.common.CommonResult;
import com.itheima.dto.AddressDto;
import com.itheima.dto.DefaultAddressDto;
import com.itheima.pojo.Address;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/addressBook")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @PutMapping("/default")
    public CommonResult defaultAddress(@RequestBody DefaultAddressDto defaultAddressDto) {
        String id = defaultAddressDto.getId();
        Boolean res = addressService.defaultAddress(id);
        if (!res) {
            return CommonResult.error("设置地址失败");
        }
        return CommonResult.success("设置地址成功");
    }

    @GetMapping("/default")
    public CommonResult getDefaultAddress() {
        Address defaultAddress = addressService.getDefaultAddress();

        if (defaultAddress == null) {
            return CommonResult.error("获取地址失败");
        }
        return CommonResult.success(defaultAddress);
    }

    @GetMapping("/list")
    public CommonResult getList() {
        List<Address> list = addressService.getList();
        if (list == null) {
            return CommonResult.error("获取地址失败");
        }
        return CommonResult.success(list);
    }

    @GetMapping("/{id}")
    public CommonResult getAddressById(@PathVariable String id) {
        Address address = addressService.getAddressById(id);
        if (address == null) {
            return CommonResult.error("获取地址失败");
        }
        return CommonResult.success(address);
    }

    @DeleteMapping("/{ids}")
    public CommonResult remove(@PathVariable String ids){
        boolean remove = addressService.remove(ids);
        if (!remove){
            return CommonResult.error("删除失败");
        }
        return CommonResult.success("删除成功");
    }
    @PostMapping
    public CommonResult add(@RequestBody AddressDto addressDto){
        boolean add = addressService.add(addressDto);
        if (!add){
            return CommonResult.error("添加失败");
        }
        return CommonResult.success("添加成功");
    }
    @PutMapping
    public  CommonResult update(@RequestBody AddressDto addressDto){
        boolean update = addressService.update(addressDto);
        if (!update){
            return CommonResult.error("修改失败");
        }
        return CommonResult.success("添加修改成功");

    }
}
